[wpf]如何在后台写controltemplate.triggers

来源:百度知道 编辑:UC知道 时间:2024/05/09 14:27:40
以下是我写的代码:
//Create a button
Button button = new Button();
button.Width = 100;
button.Height = 100;
button.Margin = new Thickness(10, 5, 0, 0);
button.Content = "Click Me!";
button.Click += TestButton_Click;

//Create a template
ControlTemplate template = new ControlTemplate(button.GetType());

FrameworkElementFactory canvas = new FrameworkElementFactory(typeof(Canvas));
template.VisualTree = canvas;

FrameworkElementFactory ellipse = new FrameworkElementFactory(typeof(Ellipse));
ellipse.SetValue(Ellipse.NameProperty, "templateEllipse");
ellipse.SetValue(Ellipse.WidthProperty, 100.0);
ellipse.SetValue(Ellipse.HeightProperty, 100.0);
ellipse.SetValue(Ellipse.FillProperty, new SolidColorBrush(Colors

所提问题与错误无关.

你发生问题的地方在於 Ellipse.NameProperty, 对於作为 FrameworkElementFactory, 它的 Name 属性可不是通过设置 NameProperty来设定, 而必须是在构造时完成.

对於你的代码, 只要将两行稍作修改即可:
FrameworkElementFactory ellipse = new FrameworkElementFactory(typeof(Ellipse), "templateEllipse"); // 在构造中就指定名字

// ellipse.SetValue(Ellipse.NameProperty, "templateEllipse"); 将这行注释掉